﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Routing;
using wne.Context;
using wne.core.Interface;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using wne.models;
using wne.models.Filter;
using System.IO;


namespace wne.core
{
    class equation
    {
        
        public equation left;
        public equation right;
        public int sign;
        public string mind;
        public string read(string s, tpksEntities context, DocModel doc,int step,DateTime date)
        {
            string[] str = new string[3];
            if (s.Contains("_ACCEPT"))
                return doc.accept.ToString();
            if (s.Contains("_REJECT"))
                return doc.decline.ToString();
            if (s.Contains("_GROUP"))
            {
                str = s.Split('.');
                string h = str[1];
                if (h == "_MAN")
                {
                    var q=context.User.Find(doc.doc.Current_User_ID);
                    h = str[2];
                    if (h == "Логин".ToUpper())
                        return q.Login;
                    if (h == "Фамилия".ToUpper())
                        return q.Last_Name;
                    if (h == "Имя".ToUpper())
                        return q.First_Name;
                    if (h == "Отчество".ToUpper())
                        return q.Second_Name;
                    if (h == "Email".ToUpper())
                        return q.Email;
                    if (h == "День рождения".ToUpper())
                        return q.Birth_Date.ToString();
                    if (h == "Телефон".ToUpper())
                        return q.ICQ.ToString();
                }
                var f1=context.Group.Where(x=>(x.Group_Name.ToUpper()==h.ToUpper())).First().User.Where(x=>(x.User_ID==doc.doc.Current_User_ID));
                if(f1.Count()>0)
                if (str[2].Equals("_EXIST")) return "true";
                var f = context.User_Grp_Prm_Value.Where(x => ((x.User_ID == doc.doc.Current_User_ID) && (x.Group_Field.Group.Group_Name.ToUpper() == h.ToUpper()))).ToList();
                foreach (var q in f)
                {
                    if (q.Group_Field.Field_Name.ToUpper().Equals(str[2].ToUpper()))
                        return q.Field_Value;
                }
                return "false";
            }
            else
                if (s.Contains("_OUR"))
                {
                    str = s.Split('.');
                    str[0] = str[1];
                    str[1] = str[2];
                    if (str[0].Equals("TIME"))
                    {
                        if (str[1] != null)
                        {
                            if (str[1].Equals("_OUTTIME"))
                                if ((DateTime.Now - doc.doc.Create_Date).Hours > Int16.Parse(context.Way_Prm.Where(x => ((x.Way_ID == doc.doc.Way_ID) && (x.Prm_Name == "TIME"))).First().Prm_Value))
                                    return "true";
                            return "false";
                        }
                        else return context.Way_Prm.Where(x => ((x.Way_ID == doc.doc.Way_ID) && (x.Prm_Name == "TIME"))).First().Prm_Value;


                    }
                    else
                    {
                        var f = context.Way_Prm.Where(x => ((x.Way_ID == doc.doc.Way_ID))).ToList();
                        if (f.Count > 0)
                        {
                            foreach (var q in f)
                            {
                                if (q.Prm_Name.ToUpper().Equals(str[0].ToUpper()))
                                    return q.Prm_Value;
                            }
                        }
                        else
                            return "false";
                    }
                }
                else
                    if (s.Contains("_THIS"))
                    {
                        str = s.Split('.');
                        str[0] = str[1];
                        str[1] = str[2];
                    }
            var prm = context.Step_Prm.Where(x=>(x.Step_ID==step));
            foreach (var q in prm)
            {
                if (q.Prm_Name.ToUpper() == str[0].ToUpper())
                {
                    if (str[0] == "TIME")
                    {
                        if (str[1] != null)
                        {
                            if (str[1].Equals("_OUTTIME"))
                                if ((DateTime.Now - date).Hours > Int16.Parse(q.Prm_Value))
                                    return "true";
                            return "false";
                        }
                        else return q.Prm_Value;
                    }
                    else return q.Prm_Value;
                }
            }
            var fld = context.Step_Field.Where(x => (x.Step_ID == step));
            foreach (var q in fld)
            {
                if (q.Field_Name.ToUpper() == str[0].ToUpper())
                {
                    var w = context.Doc_Data.Where(x => ((x.Field_Type == q.Cntr) && (x.Doc_ID == doc.doc.Doc_ID))).First();
                        if (str[1] != null)
                        {
                            if (str[1].Equals("_Add"))
                                if(w.Value!=null)
                                    return "true";
                            return "false";
                        }
                        else return w.Value;
                }
            }
            if (s.Contains("^"))
            {
                str = s.Split('^');
                s = str[1];
            }
                return s;
        }
        public int import(String s)
        {
            s=s.ToUpper();
            int s1=0;
            int s2=0;
            s=s.Trim(' ', '\t', '\n');
            bool flag = false;
            while (s2 < s.Length)
            {
                if (s[s2] == '(')
                {
                    int n = 1;
                    s2++;
                    while (n > 0)
                    {
                        if (s[s2] == '(') n++;
                        if (s[s2] == ')') n--;
                        s2++;
                    }
                }
                else
                {
                    while ((s2<s.Length)&&(s[s2] != '|') && (s[s2] != '&') && (s[s2] != '(') && (s[s2] != 0)) s2++;
                }
                if ((s2<s.Length)&&(s[s2] == '|'))
                {
                    sign = -1;
                    left = new equation();
                    left.import(s.Substring(s1, s2));
                    right=new equation();
                    right.import(s.Substring(s2+2,s.Length-s2-2));
                    return 0;
                }
                else s2++;
            }
            s2=0;
            while (s2 < s.Length)
            {
                if (s[s2] == '(')
                {
                    int n = 1;
                    s2 = 1;
                    while (n > 0)
                    {
                        if (s[s2] == '(') n++;
                        if (s[s2] == ')') n--;
                        s2++;
                    }
                }
                else
                {
                    while ((s2 < s.Length) && (s[s2] != '|') && (s[s2] != '&') && (s[s2] != '(') && (s[s2] != 0)) s2++;
                }
                if ((s2 < s.Length) && (s[s2] == '&'))
                {
                    sign = 1;
                    left = new equation();
                    left.import(s.Substring(s1, s2));
                    right=new equation();
                    right.import(s.Substring(s2+2,s.Length-s2-2));
                    return 0;
                }
                else s2++;
            }
            if(s[0]=='(')
            {
                import(s.Substring(1,s.Length-2));
                return 0;
            }
            else
                mind=s;

  
         return 0;   
        }
        public bool count(tpksEntities context, DocModel doc, int nstep, DateTime date)
        {
            if (sign == 1)
                return (left.count(context, doc, nstep, date) && right.count(context, doc, nstep, date));
            else
                if (sign == -1)
                    return (left.count(context, doc, nstep, date) || right.count(context, doc, nstep, date));
                else
                {
                    string []s=new string[2];
                    s[0] = "qq";
                    s[1] = "qq";
                    if (mind.Contains("!="))
                    {
                        s = mind.Split('!');
                        s[1] = s[1].Substring(1);
                        sign = 0;
                    }
                    else
                        if (mind.Contains("="))
                        {
                            s = mind.Split('=');
                            sign = 1;
                        }
                        else
                            if (mind.Contains(">"))
                            {
                                s = mind.Split('>');
                                sign = 2;
                            }
                            else
                                if (mind.Contains("<"))
                                {
                                    s = mind.Split('<');
                                    sign = 3;
                                }
                                else
                                {
                                    s[0] = mind;
                                    sign = 4;
                                }
                    s[0] = read(s[0], context, doc, nstep, date).ToUpper();
                    if(sign!=4)
                        s[1] = read(s[1], context, doc, nstep, date);
                    if (sign == 4)
                    {
                        if (s[0][0] == 'F')
                            return false;
                        else
                            return true;
                    }
                    else
                        if (sign == 3)
                        {
                            return Double.Parse(s[0]) < Double.Parse(s[1]);
                        }
                        else
                        if (sign == 2)
                        {
                            return Double.Parse(s[0]) > Double.Parse(s[1]);
                        }
                        else
                            if (sign == 1)
                            {
                                return s[0] == s[1];
                            }
                            else
                                return s[0] != s[1];
                                
                }

        }
    }
    public class DocumentFacadeSql : DocumentFacade
    {

        #region Docs

        public override List<Smalldoc> GetFilteredDocs(DocFilter pFilter, int id)
        {
            using (var context = new tpksEntities())
            {
                var query = (from a in context.Doc select a).ToList();
                int OrderNum;
                if ((pFilter.OrderEnum == (DocOrderEnum)1) && (pFilter.IsOrderDesc == true))
                    OrderNum = 1;
                else
                {
                    if ((pFilter.OrderEnum == (DocOrderEnum)1) && (pFilter.IsOrderDesc == false))
                        OrderNum = 2;
                    else
                    {
                        if ((pFilter.OrderEnum == (DocOrderEnum)2) && (pFilter.IsOrderDesc == true))
                            OrderNum = 3;
                        else
                        {
                            if ((pFilter.OrderEnum == (DocOrderEnum)2) && (pFilter.IsOrderDesc == false))
                                OrderNum = 4;
                            else
                            {
                                OrderNum = 0;
                            }
                        }
                    }
                }
                List<models.Smalldoc> tmplist = new List<models.Smalldoc>();
                switch (OrderNum)
                {
                    case 0:
                    {
                        var Query = (from a in context.Doc
                            join b in context.History on a.Doc_ID equals b.Doc_ID
                            where a.Current_User_ID == id
                            select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                        foreach (var item in Query)
                        {
                            if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((byte)item.FullRejectFlag[0] & (byte)64) == (byte)64))
                            {
                                Smalldoc tmpDoc = new Smalldoc();
                                tmpDoc.id = item.id;
                                tmpDoc.name = item.name;
                                tmpDoc.came = item.came;
                                tmpDoc.remain = item.came.AddDays(1);
                                tmplist.Add(tmpDoc);
                            }
                        }
                        if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                            return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                        else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                            return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                        else
                            return tmplist;
                    }
                    case 1:
                    {
                        var Query = (from a in context.Doc
                                    join b in context.History on a.Doc_ID equals b.Doc_ID
                                    where a.Current_User_ID == id
                                    orderby a.Doc_Name
                                     select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                        foreach (var item in Query)
                        {
                            if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((byte)item.FullRejectFlag[0] & (byte)64) == (byte)64))
                            {
                                Smalldoc tmpDoc = new Smalldoc();
                                tmpDoc.id = item.id;
                                tmpDoc.name = item.name;
                                tmpDoc.came = item.came;
                                tmpDoc.remain = item.came.AddDays(1);
                                tmplist.Add(tmpDoc);
                            }
                        }
                        if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count+pFilter.StartIndex<=tmplist.Count))
                            return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                        else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                            return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                        else
                            return tmplist;
                    }
                    case 2:
                    {
                        var Query = (from a in context.Doc
                                    join b in context.History on a.Doc_ID equals b.Doc_ID
                                    where a.Current_User_ID == id
                                    orderby a.Doc_Name descending
                                     select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                        foreach (var item in Query)
                        {
                            if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((byte)item.FullRejectFlag[0] & (byte)64) == (byte)64))
                            {
                                Smalldoc tmpDoc = new Smalldoc();
                                tmpDoc.id = item.id;
                                tmpDoc.name = item.name;
                                tmpDoc.came = item.came;
                                tmpDoc.remain = item.came.AddDays(1);
                                tmplist.Add(tmpDoc);
                            }
                        }
                        if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                            return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                        else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                            return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                        else
                            return tmplist;
                    }
                    case 3:
                    {
                        var Query = (from a in context.Doc
                                    join b in context.History on a.Doc_ID equals b.Doc_ID
                                    where a.Current_User_ID == id
                                    orderby b.Date
                                     select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                        foreach (var item in Query)
                        {
                            if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((byte)item.FullRejectFlag[0] & (byte)64) == (byte)64))
                            {
                                Smalldoc tmpDoc = new Smalldoc();
                                tmpDoc.id = item.id;
                                tmpDoc.name = item.name;
                                tmpDoc.came = item.came;
                                tmpDoc.remain = item.came.AddDays(1);
                                tmplist.Add(tmpDoc);
                            }
                        }
                        if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                            return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                        else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                            return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                        else
                            return tmplist;
                    }
                    case 4:
                    {
                        var Query = (from a in context.Doc
                                    join b in context.History on a.Doc_ID equals b.Doc_ID
                                    where a.Current_User_ID == id
                                    orderby b.Date descending
                                     select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                        foreach (var item in Query)
                        {
                            if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((byte)item.FullRejectFlag[0] & (byte)64) == (byte)64))
                            {
                                Smalldoc tmpDoc = new Smalldoc();
                                tmpDoc.id = item.id;
                                tmpDoc.name = item.name;
                                tmpDoc.came = item.came;
                                tmpDoc.remain = item.came.AddDays(1);
                                tmplist.Add(tmpDoc);
                            }
                        }
                        if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                            return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                        else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                            return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                        else
                            return tmplist;
                    }
                    default:
                    {
                        return tmplist;
                    }

                }
            }
        }

        /*public override List<Smalldoc> GetFilteredDocsAlive() { return null; }*/

        public override List<Smalldoc> GetFilteredDocsAvailable(DocFilter pFilter, int id)
        {
            using (var context = new tpksEntities())
            {
                int OrderNum;
                if ((pFilter.OrderEnum == (DocOrderEnum)1) && (pFilter.IsOrderDesc == true))
                    OrderNum = 1;
                else
                {
                    if ((pFilter.OrderEnum == (DocOrderEnum)1) && (pFilter.IsOrderDesc == false))
                        OrderNum = 2;
                    else
                    {
                        if ((pFilter.OrderEnum == (DocOrderEnum)2) && (pFilter.IsOrderDesc == true))
                            OrderNum = 3;
                        else
                        {
                            if ((pFilter.OrderEnum == (DocOrderEnum)2) && (pFilter.IsOrderDesc == false))
                                OrderNum = 4;
                            else
                            {
                                OrderNum = 0;
                            }
                        }
                    }
                }
                List<models.Smalldoc> tmplist = new List<models.Smalldoc>();
                switch (OrderNum)
                {
                    case 0:
                        {
                            var Query = (from a in context.Doc
                                        join b in context.History on a.Doc_ID equals b.Doc_ID
                                        where a.Current_User_ID == id
                                        select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                            foreach (var item in Query)
                            {
                                if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((int)item.FullRejectFlag[0] & (int)32) == (int)32))
                                {
                                    Smalldoc tmpDoc = new Smalldoc();
                                    tmpDoc.id = item.id;
                                    tmpDoc.name = item.name;
                                    tmpDoc.came = item.came;
                                    tmpDoc.remain = item.came.AddDays(1);
                                    tmplist.Add(tmpDoc);
                                }
                            }
                            if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                            else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                            else
                                return tmplist;
                        }
                    case 1:
                        {
                            var Query = (from a in context.Doc
                                        join b in context.History on a.Doc_ID equals b.Doc_ID
                                        where a.Current_User_ID == id
                                        orderby a.Doc_Name
                                         select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                            foreach (var item in Query)
                            {
                                if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((int)item.FullRejectFlag[0] & (int)32) == (int)32))
                                {
                                    Smalldoc tmpDoc = new Smalldoc();
                                    tmpDoc.id = item.id;
                                    tmpDoc.name = item.name;
                                    tmpDoc.came = item.came;
                                    tmpDoc.remain = item.came.AddDays(1);
                                    tmplist.Add(tmpDoc);
                                }
                            }
                            if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                            else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                            else
                                return tmplist;
                        }
                    case 2:
                        {
                            var Query = (from a in context.Doc
                                        join b in context.History on a.Doc_ID equals b.Doc_ID
                                        where a.Current_User_ID == id
                                        orderby a.Doc_Name descending
                                         select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                            foreach (var item in Query)
                            {
                                if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((int)item.FullRejectFlag[0] & (int)32) == (int)32))
                                {
                                    Smalldoc tmpDoc = new Smalldoc();
                                    tmpDoc.id = item.id;
                                    tmpDoc.name = item.name;
                                    tmpDoc.came = item.came;
                                    tmpDoc.remain = item.came.AddDays(1);
                                    tmplist.Add(tmpDoc);
                                }
                            }
                            if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                            else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                            else
                                return tmplist;
                        }
                    case 3:
                        {
                            var Query = (from a in context.Doc
                                        join b in context.History on a.Doc_ID equals b.Doc_ID
                                        where a.Current_User_ID == id
                                        orderby b.Date
                                         select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                            foreach (var item in Query)
                            {
                                if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((int)item.FullRejectFlag[0] & (int)32) == (int)32))
                                {
                                    Smalldoc tmpDoc = new Smalldoc();
                                    tmpDoc.id = item.id;
                                    tmpDoc.name = item.name;
                                    tmpDoc.came = item.came;
                                    tmpDoc.remain = item.came.AddDays(1);
                                    tmplist.Add(tmpDoc);
                                }
                            }
                            if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                            else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                            else
                                return tmplist;
                        }
                    case 4:
                        {
                            var Query = (from a in context.Doc
                                        join b in context.History on a.Doc_ID equals b.Doc_ID
                                        where a.Current_User_ID == id
                                        orderby b.Date descending
                                         select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                            foreach (var item in Query)
                            {
                                if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((int)item.FullRejectFlag[0] & (int)32) == (int)32))
                                {
                                    Smalldoc tmpDoc = new Smalldoc();
                                    tmpDoc.id = item.id;
                                    tmpDoc.name = item.name;
                                    tmpDoc.came = item.came;
                                    tmpDoc.remain = item.came.AddDays(1);
                                    tmplist.Add(tmpDoc);
                                }
                            }
                            if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                            else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                            else
                                return tmplist;
                        }
                    default:
                        {
                            return tmplist;
                        }

                }
            }
        }

        public override List<Smalldoc> GetFilteredDocsDone(DocFilter pFilter, int id)
        {
            using (var context = new tpksEntities())
            {
                //var query = (from a in context.History select a).ToList();
                int OrderNum;
                if ((pFilter.OrderEnum == (DocOrderEnum)1) && (pFilter.IsOrderDesc == true))
                    OrderNum = 1;
                else
                {
                    if ((pFilter.OrderEnum == (DocOrderEnum)1) && (pFilter.IsOrderDesc == false))
                        OrderNum = 2;
                    else
                    {
                        if ((pFilter.OrderEnum == (DocOrderEnum)2) && (pFilter.IsOrderDesc == true))
                            OrderNum = 3;
                        else
                        {
                            if ((pFilter.OrderEnum == (DocOrderEnum)2) && (pFilter.IsOrderDesc == false))
                                OrderNum = 4;
                            else
                            {
                                OrderNum = 0;
                            }
                        }
                    }
                }
                List<models.Smalldoc> tmplist = new List<models.Smalldoc>();
                switch (OrderNum)
                {
                    case 0:
                        {
                            var Query = (from a in context.Doc
                                        join b in context.History on a.Doc_ID equals b.Doc_ID
                                         where a.Current_User_ID == id
                                        select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag=a.Full_Reject_Flag}).ToList();
                            foreach (var item in Query)
                            {
                                if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((int)item.FullRejectFlag[0] & (int)16) == (int)16))
                                {
                                    Smalldoc tmpDoc = new Smalldoc();
                                    tmpDoc.id = item.id;
                                    tmpDoc.name = item.name;
                                    tmpDoc.came = item.came;
                                    tmpDoc.remain = item.came.AddDays(1);
                                    tmplist.Add(tmpDoc);
                                }
                            }
                            if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                            else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                            else
                                return tmplist;
                        }
                    case 1:
                        {
                            var Query = (from a in context.Doc
                                        join b in context.History on a.Doc_ID equals b.Doc_ID
                                        //where a.Current_User_ID == id && (a.Full_Reject_Flag == "2" || a.Full_Reject_Flag == "4"|| a.Full_Reject_Flag == "8" || a.Full_Reject_Flag == "16")
                                         where a.Current_User_ID == id 
                                        orderby a.Doc_Name
                                         select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag}).ToList();
                            foreach (var item in Query)
                            {
                                if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((int)item.FullRejectFlag[0] & (int)16) == (int)16))
                                {
                                    Smalldoc tmpDoc = new Smalldoc();
                                    tmpDoc.id = item.id;
                                    tmpDoc.name = item.name;
                                    tmpDoc.came = item.came;
                                    tmpDoc.remain = item.came.AddDays(1);
                                    tmplist.Add(tmpDoc);
                                }
                            }
                            if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                            else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                            else
                                return tmplist;
                        }
                    case 2:
                        {
                            var Query = (from a in context.Doc
                                        join b in context.History on a.Doc_ID equals b.Doc_ID
                                         where a.Current_User_ID == id
                                        orderby a.Doc_Name descending
                                        select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag=a.Full_Reject_Flag }).ToList();
                            foreach (var item in Query)
                            {
                                if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((int)item.FullRejectFlag[0] & (int)16) == (int)16))
                                {
                                    Smalldoc tmpDoc = new Smalldoc();
                                    tmpDoc.id = item.id;
                                    tmpDoc.name = item.name;
                                    tmpDoc.came = item.came;
                                    tmpDoc.remain = item.came.AddDays(1);
                                    tmplist.Add(tmpDoc);
                                }
                            }
                            if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                            else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                            else
                                return tmplist;
                        }
                    case 3:
                        {
                            var Query = (from a in context.Doc
                                        join b in context.History on a.Doc_ID equals b.Doc_ID
                                         where a.Current_User_ID == id
                                        orderby b.Date
                                         select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                            foreach (var item in Query)
                            {
                                if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((int)item.FullRejectFlag[0] & (int)16) == (int)16))
                                {
                                    Smalldoc tmpDoc = new Smalldoc();
                                    tmpDoc.id = item.id;
                                    tmpDoc.name = item.name;
                                    tmpDoc.came = item.came;
                                    tmpDoc.remain = item.came.AddDays(1);
                                    tmplist.Add(tmpDoc);
                                }
                            }
                            if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                            else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                            else
                                return tmplist;
                        }
                    case 4:
                        {
                            var Query = (from a in context.Doc
                                        join b in context.History on a.Doc_ID equals b.Doc_ID
                                         where a.Current_User_ID == id 
                                        orderby b.Date descending
                                         select new { name = a.Doc_Name, id = a.Doc_ID, came = b.Date, FullRejectFlag = a.Full_Reject_Flag }).ToList();
                            foreach (var item in Query)
                            {
                                if (((item.name.IndexOf(pFilter.SearchString) > -1) || (pFilter.SearchString == "")) && (((int)item.FullRejectFlag[0] & (int)16) == (int)16))
                                {
                                    Smalldoc tmpDoc = new Smalldoc();
                                    tmpDoc.id = item.id;
                                    tmpDoc.name = item.name;
                                    tmpDoc.came = item.came;
                                    tmpDoc.remain = item.came.AddDays(1);
                                    tmplist.Add(tmpDoc);
                                }
                            }
                            if (pFilter.StartIndex != null & pFilter.Count != null & (pFilter.Count + pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, (int)pFilter.Count);
                            else if (pFilter.StartIndex != null & (pFilter.StartIndex <= tmplist.Count))
                                return tmplist.GetRange((int)pFilter.StartIndex, tmplist.Count - (int)pFilter.StartIndex);
                            else
                                return tmplist;
                        }
                    default:
                        {
                            return tmplist;
                        }

                }
            }
        }

        public override DocModel GetDocById(int id, int userId, int page)
        {

            // Вася, перепиши метод, он намного сложнее, чем ты думал. (Кристина и Руслан)
            // за подробностями к Кристине.


            using (var context = new tpksEntities())
            {
                DocModel doc = new DocModel();
                doc.doc = context.Doc.Find(id);
                doc.fields=new List<DocField>();
                var query = context.Step_Field.Include("Doc_Data").Where(x => x.Doc_Data.Any(y=>y.Doc_ID == id)).ToList();
                foreach (var qq in query)
                {
                    foreach (var q in qq.Doc_Data)
                    {
                        if (q.Doc_ID == id)
                        {
                            DocField df = new DocField();
                            df.Field = q;
                            df.type = qq;
                            doc.fields.Add(df);
                        }
                    }
                }
                return doc;
            }
        }

        public override int DeleteDoc(int id) 
        {
                    using (var context = new tpksEntities())
                    {
                        try
                        {
                            context.Doc.Remove(context.Doc.FirstOrDefault(x => x.Doc_ID.Equals(id)));
                            context.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            return 1;
                        }
                        //return pIdRoute;
                        return 0;
                    }
        }

        public override int CreateDoc(DocModel pDocModel)
        {
            using (var context = new tpksEntities())
            {
                //pDocModel.accept = false;
                //pDocModel.decline = false;
                //pDocModel.fields
                pDocModel.doc.Create_Date = DateTime.Now;
                pDocModel.doc.Current_Step = 0;
                /// pDocModel.doc.Current_User_ID = 1048;//нада
                //pDocModel.doc.Doc_Name = "qeqq";
                pDocModel.doc.Doc_Type = 0;
                pDocModel.doc.Full_Reject_Flag = ((char)(1 | 64)).ToString();
                //pDocModel.doc.Owner_ID = 1048;//нада
                pDocModel.doc.To_Doc_Path = "";
                context.Doc.Add(pDocModel.doc);
                context.SaveChanges();
                pDocModel.fields = new List<DocField>();
                var dd = context.Step_Field.Where(x => ((x.Step.Step_Nmbr == 0) && (x.Step.Way_ID == pDocModel.doc.Way_ID)));
                foreach (var q in dd)
                {
                    Context.Doc_Data d = new Doc_Data();
                    d.Doc_ID = pDocModel.doc.Doc_ID;
                    d.Field_Type = q.Cntr;
                    d.Title = q.Field_Name;
                    d.Value = "";
                    context.Doc_Data.Add(d);
                    DocField df = new DocField();
                    df.Field = d;
                    df.type = q;
                    pDocModel.fields.Add(df);
                }
                context.SaveChanges();
                Context.History h = new Context.History();
                h.Date = DateTime.Now;
                h.Doc_ID = pDocModel.doc.Doc_ID;
                h.End_Flag = "0";
                h.Step_Nmbr = 0;
                context.History.Add(h);
                context.SaveChanges();
                return pDocModel.doc.Doc_ID;



            }

        }
        public override DocModel StartDoc(DocModel pDocModel)
        {
            using (var context = new tpksEntities())
            {
                pDocModel.doc.Create_Date = DateTime.Now;
                pDocModel.doc.Current_Step = 0;
                pDocModel.doc.Doc_Type = 0;
                pDocModel.doc.Full_Reject_Flag = ((char)(1 | 64)).ToString();
                pDocModel.doc.To_Doc_Path = "";
                pDocModel.fields = new List<DocField>();
                var dd = context.Step_Field.Where(x => ((x.Step.Step_Nmbr == 0) && (x.Step.Way_ID == pDocModel.doc.Way_ID)));
                foreach (var q in dd)
                {
                    Context.Doc_Data d = new Doc_Data();
                    d.Field_Type = q.Cntr;
                    d.Title = q.Field_Name;
                    d.Value = "";
                    DocField df = new DocField();
                    df.Field = d;
                    df.type = q;
                    pDocModel.fields.Add(df);
                }
                return pDocModel;



            }

        }
        public override int CreateDoc2(DocModel pDocModel)
        {
            using (var context = new tpksEntities())
            {
                context.Doc.Add(pDocModel.doc);
                context.SaveChanges();
                foreach (var q in pDocModel.fields)
                {
                    q.Field.Doc_ID = pDocModel.doc.Doc_ID;
                    context.Doc_Data.Add(q.Field);
                }
                context.SaveChanges();
                Context.History h = new Context.History();
                h.Date = DateTime.Now;
                h.Doc_ID = pDocModel.doc.Doc_ID;
                h.End_Flag = "0";
                h.Step_Nmbr = 0;
                context.History.Add(h);
                context.SaveChanges();
                return pDocModel.doc.Doc_ID;


            }

        }
        public override int UpdateDoc(DocModel pDocModel) 
        {
            
            using (var context = new tpksEntities())
            {
                context.Doc.Find(pDocModel.doc.Doc_ID).Full_Reject_Flag = ((char)65).ToString();
                foreach (var q in pDocModel.fields)
                {
                    context.Doc_Data.Find(q.Field.Cntr).Value = q.Field.Value;
                    context.SaveChanges();
                }
            }
            return 1; 
        }

        //public int Loadfile(int dd,Htt)

        public bool check(RouteModel rm,User user,tpksEntities context)
        {
            equation eq = new equation();
            Step newstep = context.Step.Where(x => ((x.Way_ID == rm.RouteId) && (x.Step_Nmbr == 0))).First();
            string crits = newstep.Step_Prm.Where(x => (x.Field_Type == 34)).First().Prm_Value;
            DocModel ddoc = new DocModel();
            ddoc.doc = new Doc();
            ddoc.doc.Current_User_ID = user.User_ID;
            eq.import(crits);
            return (eq.count(context, ddoc, 0, DateTime.Now));
           
        }

        public override int DocGo(DocModel ddoc) 
        {
            using (var context = new tpksEntities())
            {
                //var users = context.User_Grp_Prm_Value.ToList();
                var doc = context.Doc.Find(ddoc.doc.Doc_ID);
               // Route =context.Doc.Find(id);
                AdminFacadeSql af = new AdminFacadeSql();
                RouteModel rm = af.GetRouteById(doc.Way_ID);
                //doc.Way_ID = 1113;
                var hist = context.History.Where(x => (x.Doc_ID == doc.Doc_ID)).ToList();
                Context.History ho=new Context.History();
                ho.Date = DateTime.MinValue;
                foreach (var q in hist)
                {
                    if (q.Date > ho.Date) ho = q;
                }
                var data=context.Doc_Data.Where(x => (x.Doc_ID == doc.Doc_ID)).ToList();
                foreach (var q in data)
                {
                    Change_Table ct = new Change_Table();
                    ct.Field_Type = q.Field_Type;
                    ct.History_ID = ho.Cntr;
                    ct.Title = q.Title;
                    ct.Value = q.Value;
                    context.Change_Table.Add(ct);
                }
                var nexts = context.Step.Where(x => ((x.Step_Nmbr == doc.Current_Step) && (x.Way_ID == rm.RouteId))).First().Step_Prm.Where(x=>(x.Field_Type==33));
                equation eq = new equation();
                string prince="";
                foreach (var q in nexts)
                {
                    string s = q.Prm_Value.ToUpper();
                    s = s.Substring(s.IndexOf("if".ToUpper()) + 2, s.IndexOf("_GOTO") - (s.IndexOf("if".ToUpper()) + 2)).Trim();
                    eq.import(s);
                    if (eq.count(context, ddoc, 0, ho.Date))
                    {
                        s = q.Prm_Value.ToUpper();
                        prince = s.Substring(s.IndexOf("_GOTO") + 5).Trim();
                        break;
                    }
                } 
                Context.History hn = new Context.History();
                hn.Date = DateTime.Now;
                hn.Doc_ID = doc.Doc_ID;
                hn.End_Flag = "0";
                hn.Step_Nmbr = 1;
                if (prince == "HELL")
                {
                    ho.End_Flag ="2";
                    context.History.Add(hn);
                    context.SaveChanges();
                    DeleteDoc(doc.Doc_ID);
                    return 0;
                }
                else
                    if (prince == "HEAVEN")
                    {
                        ho.End_Flag = "4";
                        context.History.Add(hn);
                        context.SaveChanges();
                        DeleteDoc(doc.Doc_ID);
                        return 0;
                    }
                    else
                    {
                        doc.Full_Reject_Flag = ((char)33).ToString();
                        Step newstep = context.Step.Where(x => ((x.Step_Name == prince) && (x.Way_ID == rm.RouteId))).First();
                        string crits = newstep.Step_Prm.Where(x => (x.Field_Type == 34)).First().Prm_Value;
                        User user = null;
                        var users = context.User.ToList();
                        int cui = doc.Current_User_ID;
                        foreach (var q in users)
                        {
                            ddoc.doc.Current_User_ID = q.User_ID;
                            eq.import(crits);
                            if (eq.count(context, ddoc, 0, ho.Date))
                            {
                                user = q;
                                cui = q.User_ID;
                                break;
                            }
                        }
                        if (user == null)
                            return 0;
                        doc.Current_User_ID = cui;
                        doc.User = user;
                        doc.Current_Step = newstep.Step_Nmbr;
                        int stn = newstep.Step_Nmbr;
                        //var nstep = context.Step.Where(x => ((x.Step_Nmbr == stn) && (x.Way_ID == doc.Way_ID))).First();
                        //var crit = context.Step_Prm.Where(x => ((x.Step.Step_Nmbr == stn) && (x.Step.Way_ID == doc.Way_ID) && (x.Field_Type == 33))).First();
                        var pts = context.Step_Field.Where(x => ((x.Step.Way_ID == doc.Way_ID) && (x.Step.Step_Nmbr == stn))).ToList();
                        foreach (var q in pts)
                        {
                            bool less = true;
                            foreach (var w in data)
                            {
                                if (w.Step_Field.Field_Name == q.Field_Name)
                                {
                                    less = false;
                                    w.Field_Type = q.Cntr;
                                }
                            }
                            if (less)
                            {
                                Context.Doc_Data grr = new Context.Doc_Data();
                                grr.Doc_ID = doc.Doc_ID;
                                grr.Field_Type = q.Cntr;
                                grr.Title = q.Field_Name;
                                grr.Value = "";
                                context.Doc_Data.Add(grr);
                            }
                        }
                        foreach (var w in data)
                        {
                            bool more = true;
                            foreach (var q in pts)
                            {
                                if (w.Step_Field.Field_Name == q.Field_Name)
                                {
                                    more = false;
                                }
                            }
                            if (more)
                                context.Doc_Data.Remove(w);
                        }
                        /*ddoc.doc.Current_User_ID = 1048;
                        eq.count(context,ddoc,nstep.Step_ID,ho.Date);*/
                    }
              

                context.History.Add(hn);
                context.SaveChanges();

                return 1;
            }
        }

        public override Fulldoc GetFullDoc(int id)
        {
            using (var context = new tpksEntities())
            {
                var q = context.Doc.ToList();
                Fulldoc fulldoc = new Fulldoc();
                Doc doc = new Doc();
                DocModel model = new DocModel();
                     
                try
                {
                    doc = context.Doc.Find(id);
                }
                catch (System.NullReferenceException e)
                {
                    return null;
                }

                fulldoc.now = model;
                fulldoc.now.doc = doc;
                var query_doc = context.Doc.Where(x => x.Doc_ID == id).ToList();
                foreach (var q_d in query_doc)
                {
                    if (q_d.Doc_Data.Count() != 0)
                    {
                        DocField df = new DocField();
                        df.Field = q_d.Doc_Data.First();
                        df.type = q_d.Doc_Data.First().Step_Field;
                        fulldoc.now.fields.Add(df);    
                    }
                    
                }



                RouteModel route = new RouteModel();

                fulldoc.Route = route;
                fulldoc.Route.RouteId = query_doc.First().Way_ID;

                var query_way = context.Way.Where(x => x.Way_ID == fulldoc.Route.RouteId).Select(y => new { y.Way_Name }).FirstOrDefault();
                if (query_way.Way_Name!=null)
                fulldoc.Route.RouteName = query_way.Way_Name;

                var query_way_param = context.Way_Prm.Where(x => x.Way_ID == fulldoc.Route.RouteId).ToList();
                foreach (var q_w in query_way_param)
                {
                    fulldoc.Route.WayParams.Add(q_w);
                }

                fulldoc.Route.Points = new List<PointModel>();

                var query_point = context.Step.Where(x => x.Way_ID == fulldoc.Route.RouteId).ToList();
                foreach (var q_point in query_point)
                {
                    
                    PointModel point = new PointModel();
                    point.Step = q_point;
                    var query_point_prm = context.Step_Prm.Where(x => x.Step_ID == point.Step.Step_ID).ToList();
                    foreach (var q_point_prm in query_point_prm)
                    {
                        point.Params.Add(q_point_prm);
                    }

                    var query_point_field = context.Step_Field.Where(x => x.Step_ID == point.Step.Step_ID).ToList();
                    foreach (var q_point_field in query_point_field)
                    {
                        point.Fields.Add(q_point_field);
                    }
                    fulldoc.Route.Points.Add(point);
                }


                List<wne.models.History> his = new List<wne.models.History>();
                fulldoc.history = his;

                var query_history = context.History.Where(x => x.Doc_ID == id).ToList();
                foreach (var q_h in query_history)
                {
                    wne.models.History history = new wne.models.History();
                    history.step = q_h;

                    List<Context.Change_Table> c_t = new List<Context.Change_Table>();
                    history.doc_data = c_t;

                    var query_change_table = context.Change_Table.Where(x => x.History_ID == history.step.Cntr).ToList();
                    foreach (var q_c in query_change_table)
                    {
                        history.doc_data.Add(q_c);
                    }
                    fulldoc.history.Add(history);
                }



                List<Context.Migration_Info> mig_ing = new List<Context.Migration_Info>();
                fulldoc.MigrationInfo = mig_ing;

                var query_mig_info = context.Migration_Info.Where(x => x.Doc_ID == id).ToList();
                foreach (var q_mig in query_mig_info)
                {
                    fulldoc.MigrationInfo.Add(q_mig);
                }

                return fulldoc;
            }

        }

        /// <summary>
        /// Добавляет документ и маршрут из внешнего хранилища
        /// </summary>
        /// <param name="model">Важно: Плевать на ИД в модели, надо создать новый</param>
        /// <returns>Новый ид у нас в базе</returns>
        public override int AddOutDoc(Fulldoc model)
        {
            using (var context = new tpksEntities())
            {
                if (model != null)
                {
                    var query_for_id = context.Doc.Select(x => x.Doc_ID).ToList();

                    List<int> ids = new List<int>();
                    foreach (var q in query_for_id)
                    {
                        ids.Add(q);
                    }


                    Boolean check = false;
                    int id = 1;
                    while (!check)
                    {
                        foreach (int x in ids)
                        {
                            if (x == id)
                            {
                                check = false;
                                id++;
                                break;
                            }
                            else
                                check = true;

                        }
                    }
                    try
                    {
                        model.now.doc.Doc_ID = id;
                    }
                    catch (System.NullReferenceException e)
                    {
                        model.now = new DocModel();
                        model.now.doc = new Doc();
                        model.now.doc.Doc_ID = id;
                    }
                    

                    Doc Doc_to_add = new Doc();
                    Doc_to_add = model.now.doc;
                    context.Doc.Add(Doc_to_add);

                    try
                    {
                        foreach (var x in model.now.fields)
                        {
                            context.Doc_Data.Add(x.Field);
                            context.Step_Field.Add(x.type);
                            

                        }
                        
                    }
                    catch (NullReferenceException e)
                    {
                        
                    }

                    if (model.history != null)
                    {
                        foreach (wne.models.History his in model.history)
                        {
                            context.History.Add(his.step);
                            foreach (var change in his.doc_data)
                            {
                                context.Change_Table.Add(change);
                            }
                        }
                    }
                    if (model.MigrationInfo != null)
                    {
                        foreach (var miginf in model.MigrationInfo)
                        {
                            context.Migration_Info.Add(miginf);
                        }
                    }
                    try
                    {
                        context.SaveChanges();
                    }
                    catch (DbEntityValidationException e)
                    {
                        return 0;
                    }
                    
                    //int i = context.Doc.FirstOrDefault(x => x.Doc_ID.Equals(id));
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
        }
        /// <summary>
        /// Сохраняет и привязывает файл к докумету
        /// По идее в документе уже содержится ссылка на этот файл
        /// НО! Если на сервере файл с таким именем уже есть, надо сохранить файл с другим именем, и не забыть проапдейтить сам документ
        /// </summary>
        /// <param name="docId"></param>
        /// <param name="file"></param>
        /// <param name="fileName"></param>
        public override void SaveFileToDoc(int docId, byte[] file, string fileName)
        {

            using (var context = new tpksEntities())
            {
                Boolean free = false;
                int i = 0;


                while (!free)
                {
                    var query_for_name = context.Doc_Data.Where(x => (x.Field_Type == 7) && (x.Title == fileName));
                    if (query_for_name.Count() == 0)
                    {
                        free = true;
                    }
                    else
                    {
                        i++;
                        
                        int pos = fileName.LastIndexOf('.');
                        String temp = fileName.Substring(0, pos) + "_" + i +
                                      fileName.Substring(pos,fileName.Length - pos);
                        fileName = temp;
                    }
                }

                Doc_Data date = new Doc_Data();
                date.Doc_ID = docId;
                date.Field_Type = 7;
                date.Title = fileName;
                date.Value = "Что-то";

                File.WriteAllBytes(fileName, file);
               
                context.Doc_Data.Add(date);
                context.SaveChanges();
            }


                
        }
        #endregion
    }
}
